In mathematics, linear equation with one variable refers to as the equation which has a variable with a degree of 1; i.e., x1. In this example, we are using the linear equation in the form of ax +b = cx + d, where b and d are constants. We are going to teach you how to find the value or the root of xX, when the user defines a, b, c, and d.
Solve a linear equation using C++
First, let us find the equation to represent X. For that, we take the linear equation ax +b = cx + d and make x the subject.
ax – cx = d – b
X = (d – b) / (a – c)
From the equation we obtain, it is evident that a can’t be equal to c. If that happens, x tends to infinity and solutions could not be found for that.
#include<iostream> using namespace std; void LinearEquation() { double a, b, c, d, x; //User input cout << "Please enter the values for a, b, c, and d: "; cin >> a >> b >> c >> d; // Print out the user selected linear equation cout << "The linear equation is " << a << "X + " << b << " = " << c << "x + " << d << endl; // Now check for a real solution exists or not if (a == c && b == d) { cout << "There are infinite solutions possible for this equation" << endl; } // If the equation is wrong else if (a == c) { cout << "This is a wrong equation" << endl; } // Now find the value for the variable x else { x = (d - b) / (a - c); cout << "The value of x = " << x << endl; } }
Code Explanation
In the given example, first, we take the inputs to all the variables in the equation from the user. Afterward, there are 3 cases wherein the 1st case; we check whether the input a and c, b and d are equal to each other or not. If both the conditions return true, the program ends by giving a message to the user. In the 2nd condition, if the variable x values are the same, no equation exists at the end. Therefore if that condition returns true, the program ends with a response message to the user. If all the above conditions return false, then there will be a definite value for the variable x.
As we discussed previously, we use the equation to find the value of x in the else clause. Upon the successful calculation, the result will be returned to the user.
Output
Please enter the values for a, b, c, and d: 2 3 5 1
The linear equation is 2x + 3 = 5x + 1
The value of x = 0.666667
Please enter the values for a, b, c, and d: 4 5 4 5
The linear equation is 4x + 5 = 4x + 5
There are infinite solutions possible for this equation
Please enter the values for a, b, c, and d: 6 8 6 3
The linear equation is 6x + 8 = 6x + 3
This is a wrong equation